package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.GlideUtil;
import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.widget.refresh.PullToRefreshStaggeredGridView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.android.ui.widget.staggeredgrid.StaggeredGridView;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import logic.bean.TrainExamBean;
import logic.bean.TrainExamListBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;


public class TrainMyExamListMoreActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener
{
    private static final int        STATUS_REFRESH            = 0x00;
    private static final int        STATUS_LOAD               = 0x01;
	private TextView               tvTitle;
	private Button                 btnBack;
	private PullToRefreshStaggeredGridView gvExam;
	private StaggeredGridView       sgv;
	private List<TrainExamListBean> beans = new ArrayList<TrainExamListBean>();
	private TrainMyExamListAdapter examListAdapter;
	private int                     currentPage = 1;
	private int                     pageNumber  = 10;
	private int                     viewStatus;
	//加载动画
	private View                       loadingView;
	private ImageView                  loadingImg;
	private AnimationDrawable          animationDrawable;
	
	private Handler                mHandler  = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_trainexam_examlist_more_view);
		initView();
		setListener();
		initData();
	}
	
	private void initView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText("我的考试");
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		
		gvExam = (PullToRefreshStaggeredGridView) findViewById(R.id.new_trainexam_content_examlist_more);
		sgv = gvExam.getRefreshableView();
		examListAdapter = new TrainMyExamListAdapter();
		sgv.setAdapter(examListAdapter);
		
		//加载动画
		loadingView = findViewById(R.id.common_loading_layout);
		loadingImg = (ImageView) findViewById(R.id.common_loading__img);
		updateLoadingView(0);
	}
	
	private void setListener() {
		btnBack.setOnClickListener(this);
		sgv.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				String cid = QyreaderPerferencesUtil.getInstance(TrainMyExamListMoreActivity.this, Const.phone_number).getTrainIndexCid();
				Intent intent = new Intent(TrainMyExamListMoreActivity.this, TrainExamCommonWebActivity.class);
				TrainExamListBean bean = ((TrainExamListBean) arg0.getAdapter().getItem(arg2));
				intent.putExtra(DefaultConsts.title_s, "我的考试");
				intent.putExtra(DefaultConsts.req_url_s, getExamListUrl(bean.evaluationId, cid));
				startActivity(intent);
			}
		});
		gvExam.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {

			@Override
			public void onRefresh(
					PullToRefreshBase<StaggeredGridView> refreshView) {
				mHandler.post(new Runnable()
				{
					@Override
					public void run() {
						if (gvExam.isHeaderShown())
						{
							refresh();
						}
						else if (gvExam.isFooterShown())
						{
							loadMore();
						}
					}
				});
			}
		});
	}
	
	private void refresh() {
		viewStatus = STATUS_REFRESH;
		currentPage = 1;
		initData();
	}
	
	private void loadMore() {
		viewStatus = STATUS_LOAD;
		currentPage++;
		initData();
	}
	
	/**
	 * 首次进入加载动画
	 * @param flag 0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int flag) {
		switch (flag) {
			case -1:
				loadingView.setVisibility(View.VISIBLE);
				gvExam.setVisibility(View.GONE);
				if (animationDrawable != null && animationDrawable.isRunning())
				{
					animationDrawable.stop();
				}
				loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
				break;
			case 0:
				loadingView.setVisibility(View.VISIBLE);
				gvExam.setVisibility(View.GONE);
				loadingImg.setBackgroundResource(R.drawable.home_progress);
				animationDrawable = (AnimationDrawable) loadingImg.getBackground();
				animationDrawable.start();
				break;
			case 1:
				loadingView.setVisibility(View.GONE);
				gvExam.setVisibility(View.VISIBLE);
				break;
		}
	}
	
	private String getExamListUrl(int id, String cid) {
		return TrainActionHelp.getUrl() + "queryMyExamDetailsView.do?evaluationId=" + id + "&cid=" + cid;
	}
	
	private void initData() {
		String cid = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getTrainIndexCid();
		TrainActionHelp.qryMyExamList(this, cid, currentPage, pageNumber, new ObjectHttpResponseHandler<TrainExamBean>()
		{
			
			@Override
			public Type getType() {
				return new TypeToken<TrainExamBean>()
				{
				}.getType();
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				getUIHandler().post(new Runnable()
				{
					@Override
					public void run() {
						updateLoadingView(-1);
					}
				});
			}
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, final TrainExamBean arg2, String arg3) {
				loadingView.setVisibility(View.GONE);
				gvExam.setVisibility(View.VISIBLE);
				if (viewStatus == STATUS_REFRESH) {
					beans.clear();
				}
				/*getUIHandler().post(new Runnable()
	  			{
	  				@Override
	  				public void run() {
	  					updateLoadingView(1);
	  				}
	  			});*/
				if (arg2 != null && arg2.examList != null) {
					beans.addAll(arg2.examList);
				} else {
	                if (viewStatus == STATUS_LOAD) {
	                    PullToRefreshUtil.setLoadLabel(gvExam, "没有更多数据了");
	                  }
	              }
	  			examListAdapter.notifyDataSetChanged();
				gvExam.onRefreshComplete();
			}
		});
	}
	
	private void gotoRedo(int id) {
		String cid = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getTrainIndexCid();
		Intent intent = new Intent(this, TrainExamCommonWebActivity.class);
		intent.putExtra(DefaultConsts.title_s, "我的考试");
		intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + "toEvaluatingView.do?cid=" + cid + "&evaluationId=" + id + "&isRepeat=y");
		startActivity(intent);
	}
	
	private String formatUsedTime(int time) {
		int minute = 0;
		int hour = 0;
		hour = time / 60;
		minute = time % 60;
		return hour + "分" + minute + "秒";
	}
	
	private String formatHandTime(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		return sdf.format(new Date(time));
	}
	
	@Override
	public Handler getUIHandler() {
		return mHandler;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
		}

	}
	
	/*private class TrainMyExamListAdapter
	        extends
	        BaseAdapter
	{

		private TrainCoursewareHolder   holder;
		private List<TrainExamListBean> beans;

		public void initData(List<TrainExamListBean> lists) {
			beans = lists;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return (beans == null || beans.isEmpty()) ? 0 : beans.size();
		}

		@Override
		public Object getItem(int position) {
			return beans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final TrainExamListBean listBean = beans.get(position);
			if (view == null)
			{
				holder = new TrainCoursewareHolder();
				view = LayoutInflater.from(TrainMyExamListMoreActivity.this).inflate(R.layout.new_trainexam_content_2_item, null);
				holder.view2 = view.findViewById(R.id.new_trainexam_content_2_rl2);
				holder.view3 = view.findViewById(R.id.new_trainexam_content_pingRl);
				holder.sivImage = (SmartImageView) view.findViewById(R.id.new_trainexam_content_2_image);
				holder.sivImage.setDefaultImg(100);
				holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_2_title);
				holder.tvScore = (TextView) view.findViewById(R.id.new_trainexam_content_2_scores);
				holder.tvHandTime = (TextView) view.findViewById(R.id.new_trainexam_content_2_handtime);
				holder.tvUsedTime = (TextView) view.findViewById(R.id.new_trainexam_content_2_usetime);
				holder.tvRight = (TextView) view.findViewById(R.id.new_trainexam_content_2_right);
				holder.tvWrong = (TextView) view.findViewById(R.id.new_trainexam_content_2_wrong);
				holder.tvRedo = (TextView) view.findViewById(R.id.new_trainexam_content_2_redo);
				view.setTag(holder);
			}
			else
			{
				holder = (TrainCoursewareHolder) view.getTag();
			}
			if (listBean == null) return view;
			holder.tvTitle.setText(listBean.title);
			holder.view2.setVisibility(View.VISIBLE);
			holder.view3.setVisibility(View.VISIBLE);
			holder.sivImage.setImageUrl(listBean.coverImg);
			holder.tvScore.setText(Html.fromHtml("得分：<font color=#EF5416> " + listBean.userScore + "</font>"));
			holder.tvHandTime.setText("交卷时间:" + formatHandTime(listBean.handPaperTime));
			holder.tvUsedTime.setText("用时:" + formatUsedTime(listBean.usedTime));
			holder.tvRight.setText(Html.fromHtml("做对: <font color=#EF5416>" + listBean.rightNum + "</font>"));
			holder.tvWrong.setText(Html.fromHtml("做错: <font color=#EF5416>" + (listBean.examItemNum - listBean.rightNum) + "</font>"));
			if (listBean.examRepeatFlag.equals("n"))
			{
				holder.tvRedo.setVisibility(View.GONE);
			}
			holder.tvRedo.setOnClickListener(TrainMyExamListMoreActivity.this);
			holder.tvRedo.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0) {
					gotoRedo(listBean.evaluationId);
				}
			});
			return view;
		}
	}*/
	private class TrainMyExamListAdapter extends BaseAdapter {

		private TrainCoursewareHolder holder;
		//private List<TrainExamListBean> beans;

		/*public void initData(List<TrainExamListBean> lists) {
			beans = lists;
			notifyDataSetChanged();
		}*/

		@Override
		public int getCount() {
			return (beans == null || beans.isEmpty()) ? 0 : beans.size();
		}

		@Override
		public Object getItem(int position) {
			return beans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final TrainExamListBean listBean = beans.get(position);
			if (view == null) {
				holder = new TrainCoursewareHolder();
				view = LayoutInflater.from(TrainMyExamListMoreActivity.this).inflate(R.layout.new_trainexam_content_item_new, null);
				holder.view1 = view.findViewById(R.id.new_trainexam_content_item_ll1);
				holder.view2 = view.findViewById(R.id.new_trainexam_content_item_ll2);
				holder.sivImage = (ImageView) view.findViewById(R.id.new_trainexam_content_item_image);
				GlideUtil.load(TrainMyExamListMoreActivity.this, R.drawable.trainexam_default_img, holder.sivImage);
				holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_item_title);
				holder.tvTitle.setMaxLines(1);
				holder.tvRight = (TextView) view.findViewById(R.id.new_trainexam_content_item_right);
				holder.tvWrong = (TextView) view.findViewById(R.id.new_trainexam_content_item_wrong);
				holder.tvScore = (TextView) view.findViewById(R.id.new_trainexam_content_item_scores);
				holder.tvHandTime = (TextView) view.findViewById(R.id.new_trainexam_content_item_handtime);
				holder.tvRedo = (TextView) view.findViewById(R.id.new_trainexam_content_item_redo);
				view.setTag(holder);
			} else {
				holder = (TrainCoursewareHolder) view.getTag();
			}
			if (listBean == null)
				return view;
			holder.tvTitle.setText(listBean.title);
			holder.view1.setVisibility(View.GONE);
			holder.view2.setVisibility(View.VISIBLE);
			holder.tvRedo.setVisibility(View.VISIBLE);
//			holder.sivImage.setImageUrl(listBean.coverImg);
			GlideUtil.load(TrainMyExamListMoreActivity.this, listBean.coverImg,R.drawable.trainexam_default_img,holder.sivImage);
			holder.tvScore.setText(Html.fromHtml("得分:<font color=#EF5416> " + listBean.userScore + "</font>"));
			holder.tvHandTime.setText("交卷时间:" + formatHandTime(listBean.handPaperTime));
			/*holder.tvUsedTime.setText("用时:" + formatUsedTime(listBean.usedTime));*/
			holder.tvRight.setText(Html.fromHtml("做对:<font color=#EF5416>" + listBean.rightNum + "</font>"));
			holder.tvWrong.setText(Html.fromHtml("做错:<font color=#EF5416>" + (listBean.examItemNum - listBean.rightNum) + "</font>"));
			if (listBean.examRepeatFlag.equals("n")) {
				holder.tvRedo.setVisibility(View.GONE);
			}
			holder.tvRedo.setOnClickListener(TrainMyExamListMoreActivity.this);
			holder.tvRedo.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					gotoRedo(listBean.evaluationId);
				}
			});
			return view;
		}
	}
	
	private class TrainCoursewareHolder
	{
		TextView       tvTitle, tvScore, tvHandTime, tvUsedTime, tvWrong, tvRight, tvRedo;
		ImageView sivImage;
		View           view2, view3;
		View view1;
	}
	
}
